import {
  Controller,
  Post,
  UploadedFile,
  Body,
  UseInterceptors,
  Res
} from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express'
import { diskStorage } from 'multer'
import * as fs from 'fs'
import * as path from 'path'

@Controller('upload')
export class UploadController {
  @Post('/console')
  async handshake(@Body() body: any, @Res() res) {
    const { pt_md5 } = body
    const tempDir = path.join(process.cwd(), 'temp', pt_md5)

    if (fs.existsSync(tempDir)) {
      const uploaded = fs.readdirSync(tempDir)
      return res.status(200).json({ code: '0', data: uploaded.length })
    }

    fs.mkdirSync(tempDir, { recursive: true })
    return res.status(200).json({ code: '0', data: 'success' })
  }

  @Post()
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: (req, file, cb) => {
          const tempPath = path.join(process.cwd(), 'temp', req.body.pt_md5)
          if (!fs.existsSync(tempPath)) fs.mkdirSync(tempPath, { recursive: true })
          cb(null, tempPath)
        },
        filename: (req, file, cb) => {
          cb(null, `${req.body.currentChunk}.part`)
        }
      }),
    })
  )
  async upload(@UploadedFile() file, @Body() body, @Res() res) {
    const { pt_md5, chunks, fileName } = body
    const tempDir = path.join(process.cwd(), 'temp', pt_md5)
    const uploaded = fs.readdirSync(tempDir)
    if (uploaded.length == Number(chunks)) {
      const finalPath = path.join(process.cwd(), 'uploads', fileName)
      const writeStream = fs.createWriteStream(finalPath)
      for (let i = 0; i < Number(chunks); i++) {
        const chunk = fs.readFileSync(path.join(tempDir, `${i}.part`))
        writeStream.write(chunk)
        fs.unlinkSync(path.join(tempDir, `${i}.part`))
      }
      writeStream.end()
      fs.rmdirSync(tempDir)
      return res.status(200).json({ code: '0', data: '合并完成' })
    }
    return res.status(200).json({ code: '0', data: '分片上传成功' })
  }
}
